package com.ruoyi.system.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import com.ruoyi.common.core.domain.entity.SysGroup;
import com.ruoyi.common.core.domain.entity.SysUserGroup;
import com.ruoyi.system.mapper.SysGroupMapper;
import com.ruoyi.system.mapper.SysUserGroupMapper;
import com.ruoyi.system.service.ISysGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysGroupServiceImpl implements ISysGroupService {

    @Autowired
    private SysGroupMapper groupMapper;

    @Autowired
    private SysUserGroupMapper userGroupMapper;

    @Override
    @Transactional
    public int saveGroup(SysGroup sysGroup) {
        int rows =groupMapper.insert(sysGroup);
        insertGroupUsers(sysGroup);
        return rows;
    }

    @Override
    public List<SysGroup> selectGroupList(SysGroup sysGroup) {
        List<SysGroup> list = groupMapper.selectGroupList(sysGroup);
        return list;
    }

    @Override
    public SysGroup getGroupById(Long groupId) {

        return groupMapper.selectGroupById(groupId);
    }

    @Override
    @Transactional
    public int updateGroup(SysGroup sysGroup) {
        int rows =groupMapper.updateGroup(sysGroup);
        // 更新维修人员
        updateGroupUsers(sysGroup);
        return rows;
    }

    @Override
    public int deleteGroup(Long[] groupIds) {
        userGroupMapper.deleteUserGroupByGroupIds(groupIds);
        return groupMapper.deleteGroupByIds(groupIds);
    }

    private void updateGroupUsers(SysGroup sysGroup) {
        // 删除关联
        Long groupId = sysGroup.getGroupId();
        userGroupMapper.deleteUserGroupByGroupId(groupId);
        insertGroupUsers(sysGroup);
    }

    private void insertGroupUsers(SysGroup sysGroup) {
        Long[] userIds = sysGroup.getUserIds();

        if(ArrayUtil.isNotEmpty(userIds)) {
            List<SysUserGroup> list = new ArrayList<>(userIds.length);
            for (Long userId : userIds) {
                SysUserGroup userGroup = new SysUserGroup();
                userGroup.setGroupId(sysGroup.getGroupId());
                userGroup.setUserId(userId);
                list.add(userGroup);
            }

            userGroupMapper.batchUserGroup(list);

        }


    }
}
